package com.xuecheng.test.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;


public class Consumer01 {
    // 队列
    private static final String QUEUE = "HELLOWORLD";

    public static void main(String[] args) {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.255.129");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        Channel channel =null;
        try {
            connection = connectionFactory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE, true, false, false, null);

            /**
             * arg1:队列名称
             * arg2:是否自动回复
             * arg3:消费的方法
             */
            channel.basicConsume(QUEUE,true,defaultConsumer(channel));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static DefaultConsumer defaultConsumer(Channel channel){
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            /**
             *
             * @param consumerTag  消费者标签，在监听队列的地方设置
             * @param envelope 信封，可以获取一些mq信息
             * @param properties
             * @param body
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                // 交换机
                String exchange = envelope.getExchange();
                // 消息id,mq在通道中标识消息的id，可用来确认消息
                long deliveryTag = envelope.getDeliveryTag();
                // 接受消息内容
                String message = new String(body,"utf-8");
                System.out.println("recv <- mq");
                System.out.println(message);
            }
        };


        return defaultConsumer;
    }
}
